
package com.tools.cleanmaster.controller;

import android.content.Context;

import com.tools.cleanmaster.model.TrashType;
import com.tools.cleanmaster.model.db.Decode;
import com.tools.cleanmaster.model.db.ResidualTrashBean;
import com.tools.cleanmaster.model.db.TrashDB;
import com.tools.cleanmaster.model.item.AppTrashItem;
import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.LogHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class AppResidualScanner {
    private final String mPkgName;
    private final String mPkgNameEncoded;
    private final Context mContext;
    private String[] mDirRoots;

    public AppResidualScanner(Context ctx, String pkgName, String[] dirs) {
        mContext = ctx;
        mPkgName = pkgName;
        mPkgNameEncoded = Decode.encode(mPkgName);
        mDirRoots = dirs;
    }

    public List<AppTrashItem> scan() {
        String appName = "";
        TrashDB trashDb = TrashDB.getInstance();
        List<ResidualTrashBean> residualBeanList = trashDb.getResidualByPkgName(mPkgNameEncoded);
        if (FeatureConfig.DEBUG_LOG) {
            LogHelper.d(TrashScanner.SUB_TAG, residualBeanList.size() + " items from db found after pkg:" + mPkgName + " uninstalled.");
        }
        if (residualBeanList != null && !residualBeanList.isEmpty()) {
            appName = residualBeanList.get(0).softName;
            List<AppTrashItem> trashList = new ArrayList<AppTrashItem>();
            if (mDirRoots == null || mDirRoots.length == 0) {
                return null;
            }
            for (ResidualTrashBean bean : residualBeanList) {
                for (String rootDir : mDirRoots) {
                    File file = new File(rootDir, bean.filePath);
                    if (file.exists()) {
                        AppTrashItem item = new AppTrashItem();
                        item.trashType = TrashType.UNINSTALLED_APP;
                        item.appName = appName;
                        item.filePath = file.getAbsolutePath();
                        item.cleanSuggest = bean.deleteLevel;
                        trashList.add(item);
                    }
                }
            }
            return trashList;
        }
        return null;
    }
}
